import type { Editor } from "@tiptap/vue-3";
import type { Transaction } from "@tiptap/pm/state";
import { commentActions } from "../store/comment";
import { removeCommentMark } from "./commentEditor";

/**
 * 同步批注位置
 * 当文档内容变化时，更新批注的位置信息
 */
export function syncCommentPositions(
  editor: Editor,
  transaction: Transaction
): void {
  const { mapping } = transaction;

  // 遍历所有批注
  const comments = commentActions.getAllComments();

  comments.forEach((comment) => {
    // 映射位置
    const newFrom = mapping.map(comment.position.from);
    const newTo = mapping.map(comment.position.to);

    // 检查位置是否有效
    if (newFrom < 0 || newTo < 0 || newFrom >= newTo) {
      // 位置无效，删除批注和标记
      removeCommentMark(editor, comment.id);
      commentActions.deleteComment(comment.id);
    } else if (
      newFrom !== comment.position.from ||
      newTo !== comment.position.to
    ) {
      // 位置变化，更新位置
      commentActions.updateComment(comment.id, {
        position: { from: newFrom, to: newTo },
      });
    }
  });
}

